package com.lxk.mall.pms.convert.sku;

import cn.hutool.core.util.StrUtil;
import com.lxk.mall.pms.domain.vo.spu.ProductSkuPropertyVO;
import com.lxk.mall.pms.domain.PmsProductSku;
import com.lxk.mall.pms.domain.bo.spu.ProductSkuUpdateStockReqBo;
import org.dromara.common.core.utils.CollectionUtils;
import org.dromara.common.core.utils.StringUtils;
import org.dromara.common.json.utils.JsonUtils;
import org.mapstruct.Mapper;
import org.mapstruct.factory.Mappers;

import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 商品 SKU Convert
 *
 * @author 芋道源码
 */
@Mapper
public interface ProductSkuConvert {

    ProductSkuConvert INSTANCE = Mappers.getMapper(ProductSkuConvert.class);

    /**
     * 获得 SPU 的库存变化 Map
     *
     * @param items SKU 库存变化
     * @param skus SKU 列表
     * @return SPU 的库存变化 Map
     */
    default Map<Long, Integer> convertSpuStockMap(List<ProductSkuUpdateStockReqBo.Item> items,
                                                  List<PmsProductSku> skus) {
        Map<Long, Long> skuIdAndSpuIdMap = CollectionUtils.convertMap(skus, PmsProductSku::getId, PmsProductSku::getSpuId); // SKU 与 SKU 编号的 Map 关系
        Map<Long, Integer> spuIdAndStockMap = new HashMap<>(); // SPU 的库存变化 Map 关系
        items.forEach(item -> {
            Long spuId = skuIdAndSpuIdMap.get(item.getId());
            if (spuId == null) {
                return;
            }
            Integer stock = spuIdAndStockMap.getOrDefault(spuId, 0) + item.getIncrCount();
            spuIdAndStockMap.put(spuId, stock);
        });
        return spuIdAndStockMap;
    }

    default String buildPropertyKey(PmsProductSku bean) {
        if (StringUtils.isEmpty(bean.getProperties())) {
            return StrUtil.EMPTY;
        }
        List<ProductSkuPropertyVO> properties = JsonUtils.parseArray(bean.getProperties(),ProductSkuPropertyVO.class);
        properties.sort(Comparator.comparing(ProductSkuPropertyVO::getValueId));
        return properties.stream().map(m -> String.valueOf(m.getValueId())).collect(Collectors.joining());
    }



}
